#!/bin/bash -e

HOSTS=("192.168.2.150"
       "192.168.2.150"
       "192.168.2.164"
       "192.168.2.164")
USERS=("ubuntu"
       "ubuntu"
       "ubuntu"
       "ubuntu")
PASSWDS=("123456"
         "123456"
         "123456"
         "123456")
PATHS=("/home/ubuntu/Server/src/tools/client2"
       "/home/ubuntu/Server/src/tools/client2"
       "/home/ubuntu/Server/src/tools/client2"
       "/home/ubuntu/Server/src/tools/client2")

SERVER="localhost"
PORTS="7000"
ROBOTS_NUM=100
MSG_NUM=10000
LEVEL=0

usage() {
    echo "usage: $0 -s server -p ports -r robotNum -m msgNum -l level"
    echo "        server: server ip default [localhost]"
    echo "        ports: server ports like port1,port2,... default [7000]"
    echo "        robotNum: robot number default [1000]"
    echo "        msgNum: message number default [100000]"
    echo "        level: level default [0]"
}

while getopts "s:p:r:m:l:" option; do
    case "$option" in
        s)
            SERVER=$OPTARG
            ;;
        p)
            PORTS=$OPTARG
            ;;
        r)
            ROBOTS_NUM=$OPTARG
            ;;
        m)
            MSG_NUM=$OPTARG
            ;;
        l)
            LEVEL=$OPTARG
            ;;
        h)
            usage;
            exit 0;
            ;;
        :|\?)
            usage;
            exit 1;
            ;;
    esac
done

length=${#HOSTS[*]}
cardinality=$[ROBOTS_NUM/length]

#echo ${HOSTS[0]}
#echo ${HOSTS[*]}

for((i=0;i<$[length];++i))
do
    echo ${HOSTS[i]}, ${USERS[i]}, ${PASSWDS[i]}
    echo 
    expect -c '
        set timeout -1;
        spawn ssh '"${USERS[i]}@${HOSTS[i]}"';
        expect {
            "yes/no" {
                send "yes\r"; exp_continue
            }
            "*password:" {
                send '"${PASSWDS[i]}\r"'
            }
        };
        expect '${USERS[i]}*' {send "cd '${PATHS[i]}'\r"};
        expect '${USERS[i]}*' {send "nohup ./main -r '$[cardinality]' -m '$[MSG_NUM/ROBOTS_NUM*cardinality]' -s '$[i*cardinality]' -H '$SERVER' -p '$PORTS' -l '$LEVEL' > stressData_'$ROBOTS_NUM'_'$[i*cardinality]'_'$MSG_NUM'_'${HOSTS[i]}' 2>&1 && ./collect_result.sh stressData_'$ROBOTS_NUM'_'$[i*cardinality]'_'$MSG_NUM'_'${HOSTS[i]}' &\r"};
        expect '${USERS[i]}*' {send "exit\r"};
        expect eof;
    '
done
echo "execulted end..."
